using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Orchard.ContentManagement;
using Orchard.Core.Navigation.Models;
using Orchard.Core.Navigation.Services;
using Orchard.Core.Navigation.ViewModels;
using Orchard.DisplayManagement;
using Orchard.Localization;
using Orchard.Mvc.AntiForgery;
using Orchard.UI;
using Orchard.UI.Navigation;
using Orchard.Utility;
using Orchard;

using Redirect404.ViewModels;
using Redirect404.Services;
using Redirect404.Models;


namespace Redirect404.Controllers {
    public class AdminController : Controller {
        private readonly IRedirectService _redirectService;
        public IOrchardServices _services { get; set; }

        public AdminController(IRedirectService redirectService, 
                               IOrchardServices services) {
            _redirectService = redirectService;
            _services = services;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        public ActionResult Index(RedirectManagementViewModel model)
        {
            if (!_services.Authorizer.Authorize(Permissions.ManageRedirects, T("Not allowed to manage the redirects")))
                return new HttpUnauthorizedResult();

            if (model == null)
                model = new RedirectManagementViewModel();

            if (model.RedirectItemEntries == null || model.RedirectItemEntries.Count() < 1)
                model.RedirectItemEntries = _redirectService.Get().Select(CreateRedirectItemEntries).OrderBy(redirectPartEntry => redirectPartEntry.ProcessOrder).ToList();

            // need action name as this action is referenced from another action
            return View("Index", model);
        }

        private RedirectItemEntry CreateRedirectItemEntries(RedirectPart redirectPart)
        {
            return new RedirectItemEntry
            {
                RedirectEntryId = redirectPart.Id,
                RequestedURL = redirectPart.RequestedUrl,
                DestURL = redirectPart.DestUrl,
                UseRegex = redirectPart.UseRegex,
                RedirectType = redirectPart.RedirectType,
                ProcessOrder = redirectPart.ProcessOrder
            };
        }

        [HttpPost, ActionName("Index")]
        public ActionResult IndexPOST(IList<RedirectItemEntry> redirectItemEntries)
        {
            if (!_services.Authorizer.Authorize(Permissions.ManageRedirects, T("Couldn't manage the redirects")))
                return new HttpUnauthorizedResult();

            // See http://orchard.codeplex.com/workitem/17116
            if (redirectItemEntries != null)
            {
                foreach (var redirectItemEntry in redirectItemEntries)
                {
                    RedirectPart redirectPart = _redirectService.Get(redirectItemEntry.RedirectEntryId);

                    redirectPart.RequestedUrl = redirectItemEntry.RequestedURL;
                    redirectPart.DestUrl = redirectItemEntry.DestURL;
                    redirectPart.ProcessOrder = redirectItemEntry.ProcessOrder;
                    redirectPart.RedirectType = redirectItemEntry.RedirectType;
                    redirectPart.UseRegex = redirectItemEntry.UseRegex;
                }
            }

            return RedirectToAction("Index");
        }

        public ActionResult Create()
        {
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Create(RedirectManagementViewModel model)
        {
            if (!_services.Authorizer.Authorize(Permissions.ManageRedirects, T("Couldn't manage the redirects")))
                return new HttpUnauthorizedResult();

            var redirectPart = _services.ContentManager.New<RedirectPart>("RedirectItem");

            redirectPart.RequestedUrl = model.NewEntry.RequestedURL;
            redirectPart.DestUrl = model.NewEntry.DestURL;
            redirectPart.ProcessOrder = model.NewEntry.ProcessOrder;
            redirectPart.RedirectType = model.NewEntry.RedirectType;
            redirectPart.UseRegex = model.NewEntry.UseRegex;

            if (redirectPart.ProcessOrder == 0)
                redirectPart.ProcessOrder = 5;

            if (!ModelState.IsValid)
            {
                _services.TransactionManager.Cancel();
                return View("Index", model);
            }

            _services.ContentManager.Create(redirectPart);

            return RedirectToAction("Index");
        }

        [ValidateAntiForgeryTokenOrchard]
        public ActionResult Delete(int id)
        {
            if (!_services.Authorizer.Authorize(Permissions.ManageRedirects, T("Couldn't manage the redirects")))
                return new HttpUnauthorizedResult();

            RedirectPart redirectPart = _redirectService.Get(id);

            if (redirectPart != null)
            {
                    _redirectService.Delete(redirectPart);
            }

            return RedirectToAction("Index");
        }

        //bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties)
        //{
        //    return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
        //}

        //void IUpdateModel.AddModelError(string key, LocalizedString errorMessage)
        //{
        //    ModelState.AddModelError(key, errorMessage.ToString());
        //}
    }
}
